document.addEventListener("DOMContentLoaded", () => {
  const chatMessages = document.getElementById("chat-messages");
  const userInput = document.getElementById("user-input");
  const sendButton = document.getElementById("send-button");
  const chatForm = document.getElementById("chat-form");

  function simulateModel(prompt) {
    const responses = [
      "根据安全日志分析，可能存在潜在的入侵尝试。",
      "警报显示有来自未知 IP 地址的可疑登录活动。",
      "检测到多次身份验证失败，这可能表明存在暴力破解攻击。",
      "日志显示网络流量出现异常峰值，可能表明正在进行 DDoS 攻击。",
      "多个关键系统文件被修改，可能表明存在恶意软件感染。",
    ];
    return responses[Math.floor(Math.random() * responses.length)];
  }

  function addMessage(sender, message) {
    const messageElement = document.createElement("div");
    messageElement.className = `message ${sender}`;
    messageElement.textContent = message;
    chatMessages.appendChild(messageElement);
    chatMessages.scrollTop = chatMessages.scrollHeight;
  }

  if (typeof chrome !== "undefined" && chrome.runtime) {
    chrome.runtime.onMessage.addListener((request, sender, sendResponse) => {
      if (request.action === "updateContent") {
        addMessage(
          "assistant",
          `检测到新的安全告警：\n\n${request.content}\n\n请问您有什么问题吗？`
        );
      }
    });
  } else {
    console.warn("Chrome runtime environment not detected.");
  }

  chatForm.addEventListener("submit", (e) => {
    e.preventDefault();
    const userMessage = userInput.value.trim();
    if (userMessage) {
      addMessage("user", userMessage);
      userInput.value = "";

      const agentResponse = simulateModel(userMessage);
      addMessage("assistant", agentResponse);
    }
  });

  userInput.addEventListener("input", () => {
    userInput.style.height = "auto";
    userInput.style.height = userInput.scrollHeight + "px";
  });

  addMessage(
    "assistant",
    "欢迎使用安全智能助手！我正在等待新的安全告警。如果您有任何问题，请随时询问。"
  );
});
